package com.msb.mall.search.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.msb.mall.common.dto.es.SkuESModel;
import com.msb.mall.search.config.MallElasticSearchConfiguration;
import com.msb.mall.search.constant.ESConstant;
import com.msb.mall.search.service.ElastaticSearchSaveService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @Description
 * @Author liujianlin <157429758@qq.com>
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2024/7/14
 */
@Service
public class ElasticsearchServiceImpl implements ElastaticSearchSaveService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 存储商品上架信息到Elasticsearch服务的操作
     * @param skuEsModels
     * @return
     * @throws IOException
     */
    @Override
    public Boolean productStatusUp(List<SkuESModel> skuEsModels) throws IOException {
        // 创建对应索引库 --》 创建对应的Product的映射
        BulkRequest bulkRequest = new BulkRequest();

        for (SkuESModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(ESConstant.PRODUCT_INDEX);
            // 设置id
            indexRequest.id(skuEsModel.getSkuId().toString());

            // 设置文档内容 --》 将SkuEsModel转化为json字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(skuEsModel);
            indexRequest.source(json, XContentType.JSON);
            // 转换后的数据添加到批量请求中
            bulkRequest.add(indexRequest);
        }
        // 执行批量请求，向Elasticsearch服务存储数据
        BulkResponse bulk = client.bulk(bulkRequest, MallElasticSearchConfiguration.COMMON_OPTIONS);
        // 判断是否有失败的请求
        return !bulk.hasFailures();
    }
}
